package com.hmall.order.delayed;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmall.common.dto.Item;
import com.hmall.common.web.ExampleClient;
import com.hmall.order.common.constant;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    OrderLogisticsMapper orderLogisticsMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ExampleClient exampleClient;
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 功能描述: 订单定时业务
     * @return :
     * @param message
     * @param pattern
     */
    @SneakyThrows
    @Override
    public void onMessage(Message message, byte[] pattern) {
        super.onMessage(message, pattern);
        String msg = new String(message.getBody(), "UTF-8");
        String channel = new String(message.getChannel(), "UTF-8");
        String messageKey = message.toString();
        System.out.println(messageKey);

        // 业务实现
        Order order = (Order) redisTemplate.opsForValue().get(messageKey + constant.KEY_USER);
        redisTemplate.delete(messageKey + constant.KEY_USER);
        assert order != null;
        Order order1 = orderMapper.selectById(order.getId());

        QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",order.getId());
        OrderDetail orderDetail = orderDetailMapper.selectOne(wrapper);
        if (order1.getStatus()==1){
            if (orderDetail != null) {
                //如果订单取消回滚订单库商品
                exampleClient.stockMinus(order.getId(), Long.valueOf(orderDetail.getNum()));
            }
            //删除订单业务
            orderMapper.deleteById(order.getId());
            HashMap<String, Object> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("order_id",order.getId());
            //删除订单详细业务
            orderDetailMapper.deleteByMap(stringStringHashMap);
            //删除订单地址业务
            orderLogisticsMapper.deleteByMap(stringStringHashMap);
            }

        }


    }


